﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Windows.Forms;

namespace weiqijiance.温湿度大气压
{
     public class wsddqyfuli : wsddqybass
     {
         /// <summary>
         /// 打开串口
         /// </summary>
         /// <param name="sSet1">串口设置</param>
         /// <returns>是否成功打开</returns>
         public override bool openCOM(string sSet1)
         {
             bool breturn = base.openCOM(sSet1);
             commex.ReadTimeout = 500;
             commex.ReceivedBytesThreshold = 19;//达到19字节以后才开始触发串口
             commex.DataReceived += comGAS_DataReceived;
             return breturn;
         }

         public override bool SendDeviceCmd()
         {
             byte[] cCmdBuf = new byte[9] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

             cCmdBuf[0] = 0x4E;
             cCmdBuf[1] = 0x54;
             cCmdBuf[2] = 0x33;
             cCmdBuf[3] = 0x33;//
             cCmdBuf[4] = 0x53;//
             cCmdBuf[5] = 0x03;//
             cCmdBuf[6] = 0x01;//
             cCmdBuf[7] = 0x01;//
             cCmdBuf[8] = 0xFA;//

             if (commex.IsOpen)
             {
                 Byte[] m_byte = new Byte[9];
                 for (int i = 0; i < 9; i++)
                 {
                     m_byte[i] = cCmdBuf[i];
                 }
                 commex.Write(m_byte, 0, 9);
             }
             return true;
         }
         void comGAS_DataReceived(object sender, SerialDataReceivedEventArgs e)
         {
             if (commex.IsOpen)
             {
                 int n = commex.BytesToRead;//
                 byte[] buf1 = new byte[n];//声明一个临时数组存储当前来的串口数据  
                 byte[] buf = new byte[n];
                 commex.Read(buf1, 0, n);
                 if (n > 18)
                 {
                     buf = null;
                     buf = new byte[n];
                     buf1.CopyTo(buf, 0);
                     for (int i = 0; i < 6; i++)
                     {

                         if (buf[0 + i] == 0x4E && buf[1 + i] == 0x54 && buf[2 + i] == 0x33 && buf[3 + i] == 0x33 && buf[4 + i] == 0x41 && buf[5 + i] == 0x0D)
                         {

                             float.TryParse(string.Format("{0}", (buf[10 + i] * 256 + buf[11 + i]) * 0.1), out m_fWenDu);
                             float.TryParse(string.Format("{0}", (buf[12 + i] * 256 + buf[13 + i]) * 0.1), out m_fShiDu);
                             float.TryParse(string.Format("{0}", (buf[14 + i] * 256 + buf[15 + i]) * 0.1), out m_fYaLi);
                         }
                     }
                 }
             }
         }
    }
}
